export default {
	config: {
		ST_key: '',//盛途科技申请ST_key
		ST_secret: '',//盛途科技申请ST_secret
		base_url: '',//开发环境
		// base_url: '', //生产环境
		loginApi:'',
		headers: {
			'Content-Type': 'application/json;charset=UTF-8',
			'Access-Control-Allow-Origin': '*'
		},
		//通用参数
		data: {

		},
	},
	//盛途鉴权
	async ST_authentication() {
		let H = new Date().getHours()
		let time = uni.getStorageSync('ST_KEY_TIME')
		if (time != H) {
			let res = await uni.request({
				header: {
					'Content-Type': 'application/json;charset=UTF-8',
					'Access-Control-Allow-Origin': '*'
				},
				data: {
					_key: this.config.ST_key,
					_secret: this.config.ST_secret,
				},
				url: 'http://106.15.183.188:4520/project/server/api',
				method: "GET",
			})
			if (res[1]) {
				let response = res[1]
				if(response.statusCode == 200){
					let data = response.data
					if(data.code == 200){
						uni.setStorageSync('ST_KEY_TIME',H)
						return true
					}else{
						uni.showToast({
							title:data.msg,
							icon:'none'
						})
						return false
					}
				}
			}
		}else{
			return true
		}
	},
	// async await方式 es7
	async req(method, url, data = {}, headers = {}) {
		let isAuthentication = await this.ST_authentication()
		if(!isAuthentication){
			throw {
				err: 'err',
				data: '认证失败'
			}
		}
		let my_method = method
		let my_url = url.indexOf('http') == -1 ? this.config.base_url + url : url
		let my_data = {
			// token:uni.getStorageSync('JWT'),
			...this.config.data,
			...data
		}
		let my_hedaers = {
			...this.config.headers,
			...headers
		}
		if (url.indexOf(this.config.loginApi)==-1&&!(my_data.token&&my_data.token.length > 0)){
			uni.showLoading({
				title: '请重新登陆...',
				mask:true
			})

			setTimeout(() => {	
				//退出登陆
				uni.removeStorageSync('user_info')
				uni.removeStorageSync('JWT')
				uni.redirectTo({
					url: '/pages/login/login'
				})
				uni.hideLoading()
			}, 2000)

			throw {
				err: 'err'
			}

		}
		let res = await uni.request({
			header: my_hedaers,
			data: my_data,
			url: my_url,
			method: my_method,
		})

		if (res[0]) {
			uni.showToast({
				title: '网络异常，请检查网络连接情况',
				icon: 'none'
			})
			throw {
				err: 'err',
				data: res[0]
			}
		} else if (res[1]) {
			let data = res[1]
			if (data.statusCode == 200) {
				if (my_url.indexOf('https://apis.map.qq.com/') != -1) {
					return data.data.result
				} else {
					if (data.data.code == 200) {
						return data.data.data
					} else {
						uni.showToast({
							title: data.data.message,
							icon: 'none'
						})
						throw {
							err: 'err',
							data: res[1]
						}
					}
				}

			} else {
				uni.showToast({
					title: '服务异常',
					icon: 'none'
				})
				throw {
					err: 'err',
					data: res[1]
				}

			}
		}
	}
}
